package cn.edu.stu.contorller.system;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author Karl
 * @Date 2022/12/18 - 11:50
 */
@Controller
public class StaticController {

    @RequestMapping("/song/{id}.mp3")
    public void getSongMp3(@PathVariable("id")Long songId, HttpServletResponse response){
        File file = new File("mic" + File.separator + "song"+File.separator+songId+".mp3");
        file = new File(file.getAbsolutePath());
        if(!file.exists()) return;
//        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//        response.setHeader("Content-Disposition", "attachment; filename=\"" +
//                new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");

        getResource(file,response);

    }


    @RequestMapping("/img/{filename}")
    public void getSongMp3(@PathVariable("filename")String filename, HttpServletResponse response){
        File file = new File("mic" + File.separator + "song"+File.separator+filename);
        file = new File(file.getAbsolutePath());
        if(!file.exists()) return;
        getResource(file,response);

    }

    public void getResource(File file,HttpServletResponse response){
        long tot = 0;
        try {
            response.setHeader("Content-Length",String.valueOf(file.length()));

            byte[] buf = new byte[1024];
            int len = 0;
            ServletOutputStream fos = response.getOutputStream();
            // 读取类路径下的静态资源文件
            FileInputStream fis = new FileInputStream(file);
            while((len=fis.read(buf))!=-1){
                tot +=len;
                fos.write(buf,0,len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
